﻿/***************************************************************
 * 开发人员：网魂小兵@http://www.mozlite.com
 * 
 * 目标标本：4.0.30319.239
 * 
 * 最后修改：2011/11/14 21:05:14
 * ************************************************************/
namespace Mozlite.Common
{
    using System;
    using System.Linq;
    using System.Text;
    using System.Collections.Generic;
    using Mozlite.Common.Configuration;

    /// <summary>
    /// 分类管理类型。
    /// </summary>
    public class Categories
    {
        private Categories() { }

        private static string GetKey()
        {
            return string.Format("Categories::SettingsID::{0}", SiteSettings.Current.SettingsID);
        }

        private static string GetDicKey() {
            return string.Format("Categories::SettingsID::Keys::{0}", SiteSettings.Current.SettingsID);
        }

        /// <summary>
        /// 新建分类。
        /// </summary>
        /// <param name="category">分类实例对象。</param>
        /// <returns>返回创建分类状态。</returns>
        public static CreateCategoryStatus SaveCategory(Category category)
        {
            if (category.Parent.Children != null)
            {
                foreach (var cat in category.Parent.Children)
                {
                    if (cat.CategoryName.IsMatched(category.CategoryName) && cat.CategoryID != category.CategoryID)
                        return CreateCategoryStatus.DuplicateName;
                }
            }
            var status = CommonDataProvider.Current.SaveCategory(category);
            if (status == CreateCategoryStatus.Created || status == CreateCategoryStatus.Updated)
                Caches.Remove(GetKey());
            return status;
        }

        /// <summary>
        /// 获取分类列表，字典键为分类ID。
        /// </summary>
        /// <returns>返回分类列表。</returns>
        public static Dictionary<int, Category> LoadCategories()
        {
            return Caches.Get<Dictionary<int, Category>>(GetKey(), Globals.MinuteSeconds * 3, Globals.MinuteSeconds * 3, () => {
                return CommonDataProvider.Current.LoadCategories(SiteSettings.Current.SettingsID);
            });
        }

        /// <summary>
        /// 获取分类列表。
        /// </summary>
        /// <param name="type">应用程序类型。</param>
        /// <returns>返回分类列表。</returns>
        public static List<Category> GetCategories(ApplicationType type)
        {
            return (from category in LoadCategories().Values
                   where category.ApplicationType == type
                   select category).ToList<Category>();
        }

        /// <summary>
        /// 从数据库中获取分类。
        /// </summary>
        /// <param name="categoryID">分类ID。</param>
        /// <returns>返回分类实例对象。</returns>
        public static Category GetCategory(int categoryID) {
            return CommonDataProvider.Current.GetCategory(categoryID, SiteSettings.Current.SettingsID);
        }

        /// <summary>
        /// 从缓存中获取分类实例。
        /// </summary>
        /// <param name="key">分类唯一键。</param>
        /// <returns>返回分类实例对象。</returns>
        public static Category GetCategoryFromCache(string key)
        {
            if (string.IsNullOrEmpty(key))
                return null;
            return (from category in LoadCategories().Values
                    where category.Key.IsMatched(key)
                    select category).SingleOrDefault<Category>();
        }

        /// <summary>
        /// 从缓存中获取分类实例。
        /// </summary>
        /// <param name="categoryID">分类ID。</param>
        /// <returns>返回分类实例对象。</returns>
        public static Category GetCategoryFromCache(int categoryID)
        {
            Category category;
            LoadCategories().TryGetValue(categoryID, out category);
            return category;
        }

        /// <summary>
        /// 从缓存中获取多个分类列表。
        /// </summary>
        /// <param name="args">分类键参数。</param>
        /// <returns>返回分类列表。</returns>
        public static List<Category> GetCategoriesFromCache(params string[] args) {
            var categories = new List<Category>();
            if (args != null)
                return categories;
            foreach (var arg in args) {
                var category = GetCategoryFromCache(arg);
                if (category != null)
                    categories.Add(category);
            }
            return categories;
        }

        /// <summary>
        /// 获取分类ID集合，以","分割。
        /// </summary>
        /// <param name="category">分类实例对象。</param>
        /// <returns>返回分类ID集合，以","分割。</returns>
        public static string GetCategoryIDs(int categoryID)
        {
            var category = GetCategoryFromCache(categoryID);
            if (category == null)
                return null;
            return GetCategoryIDs(category).Trim(',');
        }

        private static string GetCategoryIDs(Category category) {
            string ids = category.CategoryID+",";
            if (category.Children != null)
            {
                foreach (var child in category.Children)
                {
                    ids += GetCategoryIDs(child);
                }
            }
            return ids;
        }

        /// <summary>
        /// 删除类型。
        /// </summary>
        /// <param name="categoryID">分类ID。</param>
        /// <returns>返回删除结果。</returns>
        public static CreateCategoryStatus DeleteCategory(int categoryID)
        {
            Category category = GetCategoryFromCache(categoryID);
            if (category == null)
                return CreateCategoryStatus.Deleted;
            if (category.Threads > 0)
                return CreateCategoryStatus.ThreadsNotEmpty;
            if (CommonDataProvider.Current.DeleteCategory(categoryID, category.SettingsID))
            {
                Caches.Remove(GetKey());
                return CreateCategoryStatus.Deleted;
            }
            return CreateCategoryStatus.UnknownError;
        }

        /// <summary>
        /// 计算所有分类文章数。
        /// </summary>
        public static void CalculateThreadsCount()
        {
            CommonDataProvider.Current.CalculateThreadsCount();
        }
    }
}